#!/usr/bin/env python3
"""
一键启动前后端服务
"""

import subprocess
import sys
import os
import time
import signal
import requests
from pathlib import Path

def run_command(cmd, cwd=None, shell=True):
    """运行命令"""
    return subprocess.Popen(cmd, cwd=cwd, shell=shell)

def find_npm_path():
    """查找npm路径"""
    # 常见的npm安装路径
    possible_paths = [
        "npm",  # 系统PATH中
        "C:\\Program Files\\nodejs\\npm.cmd",
        "C:\\Program Files (x86)\\nodejs\\npm.cmd",
        os.path.expanduser("~\\AppData\\Roaming\\npm\\npm.cmd"),
    ]

    for npm_path in possible_paths:
        try:
            result = subprocess.run([npm_path, '--version'],
                                  capture_output=True, text=True, shell=True, timeout=10)
            if result.returncode == 0:
                print(f"✅ 找到npm: {npm_path}, 版本: {result.stdout.strip()}")
                return npm_path
        except Exception as e:
            continue

    return None

def check_backend_health(max_retries=10):
    """检查后端服务健康状态"""
    for i in range(max_retries):
        try:
            response = requests.get("http://localhost:8002/health", timeout=2)
            if response.status_code == 200:
                print("✅ 后端服务健康检查通过")
                return True
        except:
            pass
        print(f"⏳ 等待后端服务启动... ({i+1}/{max_retries})")
        time.sleep(2)
    return False

def main():
    print("🚀 启动心理健康聊天机器人...")
    
    # 获取项目根目录
    root_dir = Path(__file__).parent
    backend_dir = root_dir / "server" / "mvp-llm-app-scaffold"
    frontend_dir = root_dir / "frontend"
    
    processes = []
    
    try:
        # 启动后端 (端口8002)
        print("📡 启动后端服务 (端口8002)...")
        backend_cmd = "python run_server.py"  # 使用专门的启动脚本
        backend_process = run_command(backend_cmd, cwd=backend_dir)
        processes.append(("后端", backend_process))

        # 等待后端服务启动并检查健康状态
        if not check_backend_health():
            print("❌ 后端服务启动失败或健康检查失败")
            raise Exception("后端服务启动失败")
        
        # 查找npm路径
        npm_path = find_npm_path()
        if not npm_path:
            print("❌ 无法找到npm命令")
            print("💡 Node.js已安装但npm不可用，请检查安装")
            print("📡 后端已启动，可以手动启动前端:")
            print(f"   cd {frontend_dir}")
            print("   npm install")
            print("   npm run dev -- --port 3000")

            # 只运行后端
            print("\n⚠️  只启动后端服务，前端需要手动启动")
        else:
            # 启动前端 (端口3000)
            print("🎨 启动前端服务 (端口3000)...")
            frontend_cmd = f'"{npm_path}" run dev -- --port 3000'
            frontend_process = run_command(frontend_cmd, cwd=frontend_dir)
            processes.append(("前端", frontend_process))
            time.sleep(2)  # 等待前端启动
        
        print("\n✅ 服务启动完成!")
        print("📡 后端地址: http://localhost:8002")
        print("🎨 前端地址: http://localhost:3000")
        print("\n按 Ctrl+C 停止所有服务...")
        
        # 等待用户中断
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n🛑 正在停止服务...")
        
        # 停止所有进程
        for name, process in processes:
            try:
                print(f"停止{name}服务...")
                process.terminate()
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                print(f"强制停止{name}服务...")
                process.kill()
            except Exception as e:
                print(f"停止{name}服务时出错: {e}")
        
        print("✅ 所有服务已停止")
        sys.exit(0)
    
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
